<?php

//set required scripts
require("HTMLFunctions.php");
require("ValidationFunctions.php");
require('ac_db.inc.php');
require('StockFunctions.php');

error_reporting(E_ERROR | E_WARNING);


//set credentials for database
setcredentials("tr2286","databases8620", "w4111b.cs.columbia.edu/ADB");

//create DB instance
$db = new Db("Proj1", "Part3");

//set email as permanent variable as it will be constantly used
$email;
$portfolioStockSelected;
$interestStockSelected;

$userInfo = array();

//ensure that input is not blank which would mean that the site is illegally accessed
if(count($_POST) == 0 && count($_GET) == 0){
	
	//if so, redirect to login
	echo "<meta http-equiv='refresh' content='0;url=http://localhost/login.php'>";
	exit;
}

//see if get information is present
if(count($_POST) == 0){
	
	//we know that we were redirected from the login page so obtain email
	$email = $_GET['email'];
	
	//declare scalars to hold most important information
	$tempInfo = $db -> getCustomerDetails($_GET['email']);
	$userInfo['firstName'] = $tempInfo['FIRST_NAME'];
	$userInfo['lastName'] = $tempInfo['LAST_NAME'];
	
	calculatePortfolioInfo($email, $db);
}
//otherwise this script redirected here via post
else{
	$email = $_POST['email'];
	$portfolioStockSelected = $_POST['portfolioStockSelected'];
	$interestStockSelected = $_POST['interestStockSelected'];
	
	//declare scalars to hold most important information
	$tempInfo = $db -> getCustomerDetails($_GET['email']);
	$userInfo['firstName'] = $tempInfo['FIRST_NAME'];
	$userInfo['lastName'] = $tempInfo['LAST_NAME'];
	
	calculatePortfolioInfo($email, $db);
}

createProfile($email, $userInfo, $db);

//function to create the profile
function createProfile($email, $userInfo, $db){
	
	//create the html beginning
	HTMLFunctions::printHTMLHead("Welcome {$userInfo['firstName']}");
	
	//create header bar
	HTMLFunctions::generateTitleBar("Your Profile", $email, $db);
	
	//call function to create the profile html
	generateProfileHTML($email, $userInfo, $db);
	
	//call function to create the end
	HTMLFunctions::printHTMLEnd();
}

//function to produce the actual html code of the main profile
function generateProfileHTML($email, $userInfo, $db){
	
	//print heading code
	echo <<<END_HTML
	
	<!--now proceed to main body-->
	<div class="content">
	<table class="tablecontent">
	<tr class="trmain">
	<td class="tdmain">
	<div class="tdmaindiv">
	
	<!--Portfolio information-->
	<h4>Portfolio</h4>
END_HTML;

	//call function to generate the porfolio html
	generatePortfolioHTML($email, $db);
		
	//print more HTML
	echo <<<END_HTML
	</div>
	</td>
	<td class="tdmain">
	<div class="tdmaindiv">
	
	<!--interest list information-->
	<h4>Interest List</h4>
	
END_HTML;

	//call funciton to display the interest list html
	generateInterestHTML($email, $db);
	
	//print more HTML
	echo <<<END_HTML
	</div>
	</td>
	<td class="tdmain">
	<div class="tdmaindiv">
	
	<!--specific information-->
	<h4>Details</h4>
END_HTML;

	//call funciton to print details
	displayUserInformation($email, $userInfo, $db);
	
	//remaining hmtl
	echo <<<END_HTML
	</div>
	</td>
	</tr>
	</table>
	</div><!--content-->
	
END_HTML;
}

//function to display overall user stats
function displayUserInformation($email, $userInfo, $db){
	
	//obtain general user info from DB
	$portfolio = $db->getPortfolioStocks($email);
	$interest = $db->getInterestStocks($email);
	
	$portfolioSize = count($portfolio);
	$interestSize = count($interest); //get interest
	$currentValue = $db->getCurrentPortfolioValue($email);
	$overallChange= $db->getOverallPortfolioChange($email); //get overall change
	
	//show detailed information
	echo <<<END_HTML
	
	<h5>Detailed Information for {$userInfo['firstName']} {$userInfo['lastName']}:</h5>
	
	<p>You have a portfolio of $portfolioSize stocks worth $currentValue dollars.</p>
	<p>The overall change in your investment is $overallChange dollars</p>
	<p>You are also interested in $interestSize further stocks.
END_HTML;
	
	//close db connection
	$db->closeSession();
	
}

//function to display the interest list information of a user in an ordered list
function generateInterestHTML($email, $db){
	
	//declare array to hold all stocks in the portfolio
	$interestStocks = $db->getInterestStocks($email);
	
	//update stocks
	foreach($interestStocks as $tempStock){
		
		//StockFunctions::getCurrentStockData($tempStock, $db);
	}
	
	//print html code for list
	echo <<<END_HTML
	<table>
		<!--titles-->
		<tr>
			<td><p>Current Stocks:</p></td>
		</tr>
		<tr>
		<!--scroll list for stocks owned-->
		<td align="top">
END_HTML;
	
	//make sure that there are stocks
	if(count($interestStocks) != 0){
			
		//print form
		print <<<END_HTML
		<p>
		<form action="stockDetail.php" method=POST>
		<select name="ticker" size="10">
	
END_HTML;
		
		//otherwise just loop through the array stocks to display them
		foreach ($interestStocks as $currentStock){
		
			echo "<OPTION>$currentStock";
		}
		
		//proceed to print the finishing tags
		echo <<<END_HTML
		</select>
		<!-- now create a hidden field that resubmits the usernmae so that the script knows what user is being passed back-->
		<input type="hidden" name="email" value="$email">
		</p>
		
		<!--submit button-->
		<p>
		<input type="submit" value="View Stock Details"></form>
		</p>
END_HTML;
	}
	
	//otherwise print that no stocks are in teh portfolio
	else{
		echo "<tr><td><p><font color=\"red\">There are no Stocks in Your Interest List</font></p></td></tr>";
	}
	
	//print final tags
	echo "</td></tr></table>";
}

//function to display the portfolio information of a user in an ordered list
function generatePortfolioHTML($email, $db){
	
	//declare array to hold all stocks in the portfolio
	$portfolioStocks = $db->getPortfolioStocks($email);
	
	if(count($portfolioStocks) > 0){
		//update stocks
		foreach($portfolioStocks as $tempStock){
		
			//StockFunctions::setCurrentStockData($ticker, $db);
		}
	}
	
	//print html code for list
	echo <<<END_HTML
	<table>
		<!--titles-->
		<tr>
			<td><p>Current Stocks:</p></td>
		</tr>
		<tr>
		<!--scroll list for stocks owned-->
		<td align="top">
END_HTML;

	//make sure that there are stocks
	if(count($portfolioStocks) != 0){
			
		//print form
		print <<<END_HTML
		<p>
		<form action="stockDetail" method=POST>
		<select name="ticker" size="10">
	
END_HTML;
		
		//otherwise just loop through the array stocks to display them
		foreach ($portfolioStocks as $currentStock){
		
			echo "<OPTION>$currentStock";
		}
		
		//proceed to print the finishing tags
		echo <<<END_HTML
		</select>
		<!-- now create a hidden field that resubmits the usernmae so that the script knows what user is being passed back-->
		<input type="hidden" name="email" value="$email">
		</p>
		
		<!--submit button-->
		<p>
		<input type="submit" value="View Stock Details"></form>
		</p>
END_HTML;
	}
	
	//otherwise print that no stocks are in teh portfolio
	else{
		echo "<tr><td><p><font color=\"red\">There are no Stocks in Your Portfolio</font></p></td></tr>";
	}
	
	//print final tags
	echo "</td></tr></table>";
}

//calculate portfolio info
function calculatePortfolioInfo($email, $db){
	
	//calculate overall value
	//get all stocks in the portfolio
	$portfolioStocks = $db->getPortfolioStocks($email);
	
	if(count($portfolioStocks) > 0){
		
		$currentOverallValue = 0;
	
		//now loop through each stock
		foreach($portfolioStocks as $currentStock){
		
			$transactionsOfStock = $db -> getUserStockTransactions();
			$stockQuantity = 0;
			$currentStockPrice = $db->getCurrentStockValue();
		
			//sum the quantity of all transactions
			foreach($transactionsOfStock as $indiTransaction){
				$tempQuantity = $db -> getTransactionQuantity($indiTransaction);
				$stockQuantity = $stockQuantity + $tempQuantity;
			}
		
			$currentOverallValue = $currentOverallValue + ($stockQuantity * $currentStockPrice);
		}
	}
	else{
		$currentOverallValue = 0;
	}
	
	
	//set overall value
	$currentAmountInvested = $db->getPortfolioAmountInvested($email);
	if($currentAmountInvested != 0){
		
		$newOverallChange = $currentOverallValue - $currentAmountInvested;
	
		$newPercentChange = $newOverallChange / $currentAmountInvested;
	}
	else{
		$newOverallChange = 0;
		$newPercentChange = 0;
	}
	
	
	$db->setCurrentPortfolioValues($email, $currentOverallValue, $newOverallChange, $newPercentChange);
	
	
}




